// pages/listendetail/listendetail.js
var that,
  api = new (require('../../utils/api.js')),
  WxParse = require('../../wxParse/wxParse.js'),
  headimg = api.getimgurl(),
  headaudio = api.getaudiourl(),
  app = getApp(),
  util = new (require('../../utils/util.js'));
const myAudio = null//wx.getBackgroundAudioManager();
// myAudio.title = that.data.data.title;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    state: 'pause',
    formatCurrentTime: '00:00',
    formatDuration: '',
    currentTime: 0,
    duration: 0,
    descshow:!0,
    sendshow: !1,
    cid:'',
    userid:'',
    index:'',
    last:'',
    next:'',
    comment:'0',
    keyword:'',
    start:0,
    pagesize:5,
    id:0,
    liked:0,
    commemArr:[],
    bookdate :[],
    collectionimg:'cancel',
    data: {
    },
    contents:'',
    checkbox: [{
      value: 60000,
      name: '1分钟',
      checked: false,

    }, {
      value: 180000,
      name: '3分钟',
      checked: false,

    }, {
      value: 300000,
      name: '5分钟',
      checked: false,
  
    }, {
      value: 600000,
      name: '10分钟',
      checked: false,
 
    }, {
      value: 1800000,
      name: '30分钟',
      checked: false,

    }, {
      value: 3600000,
      name: '1小时',
      checked: false,

    }],
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this;
    console.log(options,'rowdatarowdataoptions')
    let shareid =0
    if(options.share){
      shareid = options.share
    }
    that.setData({shareid})
    // if (options.t==1){
      
    //   myAudio.onTimeUpdate(() => {
    //     let duration = Math.ceil(myAudio.duration);
    //     let currentTime = Math.ceil(myAudio.currentTime);
    //     that.setData({
    //       duration,
    //       formatDuration: that.formatSeconds(duration),
    //       currentTime,
    //       formatCurrentTime: that.formatSeconds(currentTime),
    //     })
    //   })
    // }else{
   
    // }
    // let { currentTime }=that.data
    that.setData({ id: options.id, t: options.t||0  },()=>{
    if (app.logininfo) {
      that.getdata()
    } else {
      util.setwatcher(app, this.afterlogin)
    }
    })
    
  },
  // initaudio(duration,time){
  //   console.log('initaudio')
  //   let formatDuration = '';
  //   wx.hideLoading();
  //     duration = myAudio.duration
  //     duration = Math.ceil(duration)

  //     formatDuration = that.formatSeconds(duration)
  //     that.setData({
  //       state: 'play',
  //       duration, formatDuration
  //     })
  // myAudio.onTimeUpdate(()=>{
  //   let currentTime = Math.ceil(myAudio.currentTime);
  //   that.setData({
  //     currentTime ,
  //     formatCurrentTime: that.formatSeconds(currentTime),
  //   })
  // })
    //监听音乐暂停
    // myAudio.onPause(res => {
    //   that.setData({
    //     state: 'pause'
    //   })
    //   let {
    //     id,
    //     currentTime,
    //     formatCurrentTime
    //   } = that.data
    // })

    //监听音乐自然播放完
    // myAudio.onEnded(res => {
    //   let { next } = that.data
    //   console.log('播放完！')
    //   that.setData({
    //     state: 'pause'
    //   }, () => {
    //     setTimeout(() => {
    //       that.getnextsong()
    //     }, 1000)
    //   })
    // })
  // },

  // changenewaudio(audio){
  //   console.log('changenewaudio', audio)
  //   myAudio.stop();
  //   myAudio.src= audio.audiosrc;
  //   myAudio.title=audio.data.title;
  //   myAudio.play();
  //   myAudio.onCanplay(()=>{
  //     that.initaudio(myAudio.duration)
      
  //   })

  // },



  afterlogin: {
    token: res => {
      that.getdata()
    }
  },
  getdata(){
    // if(that.data.t!=1){
    //   wx.showLoading({
    //     title: '加载中',
    //   })
    // }
    let appletname=app.logininfo.appletname
    wx.setNavigationBarTitle({
      title: appletname  || '小巴学堂',
    })
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
    let {id,shareid}=that.data
      that.getdetail(id)
      that.getviews(id)
      that.getuserid()
      that.getcomments(id)
      if(Number(shareid)>0){
        api.checkshare(shareid,res=>{
          if(res.data.issuccess!=1){
      
          }
        
        })
    }
  },
  getuserid(){
    let {userid}=app.logininfo
    that.setData({userid})
  },
  getdetail(e){
    api.audiofindaudiobyid(e, res => {
      if (res.data.issuccess == 1) {
        // wx.showLoading({
        //   title: '加载中',
        // })
    //     detail = decodeURIComponent(detail);
    // topimg = headimg + topimg
    // WxParse.wxParse('article', 'html', detail, that, 5);
        
        let { data, iscollect, isfavor, last, next } = res.data
        let audiosrc = '', imgsrc = headimg + data.thumbpath
        if(data.src){
          audiosrc = headaudio + data.src
        }
        data.views = data.views >= 10000 ? (data.views / 10000).toFixed(1) + "万" : data.views
        data.date = util.formatDate(new Date(data.date));
        var article=that.replaceraw(decodeURIComponent(data.rawData));
        WxParse.wxParse('article', 'html', article, that, 5);
        let collectionimg=iscollect ? 'collection' :'cancel'
        let item = { data, audiosrc, imgsrc, isfavor }
        if(that.data.t!=1){
        // that.changenewaudio(item)
        }else{
          this.initaudio(myAudio.duration, that.data.t)
        }
        that.setData({ data: item, last, next, collectionimg  }, () => {
          //that.init()
          that.getcomments(e)  
         
        })
      }
    })
   // wx.hideLoading();
  },
   replaceraw(content) {
       return content.replace('rgb(', 'rgb').replace(new RegExp('rgb', 'g'), "rgb(");
   },
  getcomments(id){
    let { start, pagesize, commemArr } = that.data
    api.commentsaugetlist({ aid:id, start, pagesize},res=>{
      if(res.data.issuccess==1){
        console.log(res.data.list,'res.data.listres.data.listres.data.list')
        commemArr = res.data.list.map((x, i) => {
          // if (x.item.avatar) {
          //   x.item.avatar = headimg + x.item.avatar
          // }else{
          //   x.item.avatar ="https://www.jihemu.com/bookapi/imgs/2019-11-19/4a3c2e9708db428f8d3c2a931d04ce5f.jpeg"
          // }
          if (!x.item.username){
            x.item.username = "匿名用户" + x.item.userid
          }
          x.item.updateDate = util.formatDate(new Date(x.item.updateDate));
          return x;
        })
      that.setData({ commemArr, comment: res.data.total })
      }
    })
  },

  /**
   * 初始化
   */
  init() {
    // let { data, duration, formatDuration, formatCurrentTime, id }=that.data
    // myAudio.title = data.data.title;
    // if (myAudio.src == data.audiosrc) {
    //   myAudio.play()
    //   return
    // } else {
    //   myAudio.src = data.audiosrc;
    // }

    //播放监听
    // myAudio.onPlay(res => {
    //   if (!duration || duration==0){
    //     myAudio.duration
    //       duration = myAudio.duration
    //       console.log(duration, 'duration')
    //       duration = Math.ceil(duration)
    //       formatDuration = that.formatSeconds(duration) 
    //   }
    //   console.log(myAudio.duration,'onplay--duration')
    //   that.setData({
    //     state: 'play',
    //     duration, formatDuration
    //   },()=>{
    //     wx.hideLoading();
    //   })
    // })

    // myAudio.play()音频监听
    // myAudio.onTimeUpdate(res => {

    //   let currentTime = Math.ceil(myAudio.currentTime),
    //     formatCurrentTime = that.formatSeconds(currentTime),
    //     duration = Math.ceil(myAudio.duration),
    //     formatDuration = that.formatSeconds(duration) 
    //   that.setData({
    //     currentTime,
    //     formatCurrentTime,
    //     duration,
    //     formatDuration
    //   })

    // })

   
  },

  /**
   * 播放按钮
   */
  playAudio(e) {
    // let { data } = that.data
    // myAudio.title = data.data.title;
    // let {
    //   state
    // } = that.data;
    // if (state == 'play') {
    //   myAudio.pause()
    //   that.setData({
    //     state: 'play'
    //   })
    // } else {
    //   if (!myAudio.src) {
    //     myAudio.title = data.data.title;
    //     myAudio.src = data.audiosrc
    //     return
    //   }
    //   myAudio.play()
    //   that.setData({
    //     state: 'play'
    //   })
    // }

  },

  /**
   * 暂停按钮
   */
  // pauseAudio() {
  //   myAudio.pause()
  // },


  /**
   * 进度条事件
   */
  // sliderChange(e) {
  //   let percent = e.detail.value,
  //     {
  //       duration
  //     } = that.data;
  //   if (myAudio.paused) {
  //     myAudio.seek(percent)
  //   } else {
  //     myAudio.seek(percent)
  //   }

  // },
  // descshow(){
  //   let { descshow } = that.data
  //   that.setData({ descshow: !descshow })
  // },
// 上一曲
  // lastsong(){
  //   wx.showLoading({
  //     title: '加载中',
  //   })
  //   let {index,last,id,data}=that.data
  //   myAudio.title = data.data.title;
  //   if (last==0){
  //     wx.showToast({
  //       title: "已经是第一首了",
  //       icon: 'none',
  //       duration: 1500
  //     })
  //     return;
  //   }
  //     myAudio.seek(0)
  //     that.setData({
  //       duration:0
  //     })
  //     console.log(last,'last')
  //     that.getdetail(last)
  //     that.getviews(last)
  // },
  // getnextsong(){
  //   wx.showLoading({
  //     title: '加载中',
  //   })
  //   let { index, next,id,data } = that.data
  //   myAudio.title = data.data.title;
  //   if (next == 0) {
  //     wx.showToast({
  //       title: "已经是最后一首了",
  //       icon: 'none',
  //       duration: 1500
  //     })
  //     return;
  //   }
  //   console.log(next,'next')
  //   myAudio.seek(0)
  //   that.setData({
  //     duration: 0
  //   })
  //   that.getdetail(next)
  //   that.getviews(next)
  // },
  // 下一曲
  nextsong() {
    wx.showLoading({
      title: '加载中',
    })
    that.getnextsong()
  },
  input(e) {
    let  { contents } =that.data
    that.setData({
      contents: e.detail.value
    })
   
  },
  send(e){
    let userinfo = wx.getStorageSync("userinfo");
    console.log(userinfo,'userinfouserinfo')
    let {contents,id}=that.data
    // api.commentsauadd({ contents,aid:id},res=>{
    //   if (res.data.issuccess==1){
    //     wx.showToast({
    //       title: '评论成功',
    //     })
    //     that.getcomments(id)
    //   }else{
    //     wx.showToast({
    //       title: res.data.msg,
    //       icon: 'none',
    //       duration: 1500
    //     })
    //   }
    // })
    that.setData({ sendshow: !1})
    if (!!userinfo) {
      //获取用户信息
      wx.getUserInfo({
        success: res => {
          console.log(res, '12334131s')
          let {
            nickName,
            avatarUrl
          } = res.userInfo;
          let date = new Date();
          date = util.formatTime(date);
          //添加评论
          api.commentsauadd({
            username: nickName,
            avatarurl:avatarUrl,
            contents,
            aid:id
          }, res => {
            console.log(res, 'aabcc')
            if (res.data.issuccess == 1) {
              that.setData({ newcomment: '' ,sendshow: !1},()=>{
                that.getcomments(id) //刷新列表
              })
            } else if (res.data.msg = "wrong 包含敏感内容") {
              wx.showToast({
                title: '您输入的评论包含敏感内容，请重新输入',
                icon: 'none'
              })
            }
          })
        }
      })
    }
  },
  // 写评论
  writecomment(){
    that.setData({ sendshow:!0 })
  },
  modsend(){
    that.setData({ sendshow: !1 })
  },
  // 删除评论
  del(e){
    let { id } = e.currentTarget.dataset,{userid}=that.data,aid=that.data.id
    wx.showModal({
      title: '提示',
      content: '确定要删除评论吗',
      success: function (res) {
        if (res.confirm) {
          api.commentsaudel(id, res => {
            if (res.data.issuccess == 1) {
              console.log(res, "成功删除");
              that.getcomments(aid)
            }
          })
        }
      }
    })
  },
// 收藏和取消
  collection(e){
    let { id, collectionimg}=that.data
    if (collectionimg =='cancel'){
      api.collectionaod(id,res=>{
        if (res.data.issuccess==1){
        wx.showToast({
          title: '收藏成功',
          icon: 'none',
          duration: 1500
        })
        that.setData({ collectionimg: 'collection'})
        }
      })
    }else{
      api.collectionaod(id, res => {
      if (res.data.issuccess == 1) {
        wx.showToast({
          title: '取消收藏',
          icon: 'none',
          duration: 1500
        })
        that.setData({ collectionimg: 'cancel' })
      }
      })
    }
  },
// 音频点赞
  audiofavor(){
    let { id, data } = that.data, { isfavor } = data
    console.log(isfavor,'isfavorisfavor')
    if (isfavor) {
      console.log('取消')
      api.audiofavor( id , res => {
        if (res.data.issuccess == 1) {
          wx.showToast({
            title: '取消点赞',
            icon: 'none',
            duration: 1500
          })
          // isfavor= false
          data.isfavor= false 
          data.data.favor = data.data.favor - 1
          that.setData({ data })
        }
      })
    } else {
      console.log('成功')
      api.audiofavor( id , res => {
        if (res.data.issuccess == 1) {
          wx.showToast({
            title: '点赞成功',
            icon: 'none',
            duration: 1500
          })
          data.isfavor = true 
          data.data.favor = data.data.favor+ 1
          that.setData({ data })
        }
      })
    }
  },
  /**
   *  时间格式化
   */
  formatSeconds(value) {
    var secondTime = parseInt(value); // 秒
    var minuteTime = 0; // 分
    var hourTime = 0; // 小时
    if (secondTime >= 60) { //如果秒数大于60，将秒数转换成整数
      //获取分钟，除以60取整数，得到整数分钟
      minuteTime = parseInt(secondTime / 60);
      //获取秒数，秒数取佘，得到整数秒数
      secondTime = parseInt(secondTime % 60);
     
      //如果分钟大于60，将分钟转换成小时
      if (minuteTime >= 60) {
        //获取小时，获取分钟除以60，得到整数小时
        hourTime = parseInt(minuteTime / 60);
        //获取小时后取佘的分，获取分钟除以60取佘的分
        minuteTime = parseInt(minuteTime % 60);
       
      }
    }
    minuteTime = minuteTime + hourTime * 60;
    if (secondTime < 10) {
      secondTime = "0" + secondTime
    }
    if (minuteTime < 10) {
      minuteTime = "0" + minuteTime
    }
    // hourTime = hourTime.length == 1 ? '0' + hourTime : hourTime,
    //   minuteTime = minuteTime.length == 1 ? '0' + minuteTime : minuteTime,
    //   secondTime = secondTime.length == 1 ? '0' + secondTime : secondTime;
    var result = minuteTime + ':' + secondTime;
    return result;
  },

// 添加浏览量
getviews(id){
  api.audioaddview(id, res => {
    console.log(res.data)
    if (res.data.issuccess == 1) {

    }
  })
},
// 点赞
  liked(e){
    let { commemArr } = that.data, { index } = e.currentTarget.dataset, { isfavor, item } = commemArr[index], { id, favor  } = item
    if (isfavor){
      api.commentsaufavor({ audioid: id }, res => {
        if (res.data.issuccess == 1) {
          wx.showToast({
            title: '取消点赞',
            icon: 'none',
            duration: 1500
          })
          commemArr[index]['isfavor'] = false
          commemArr[index]['item']['favor'] = commemArr[index]['item']['favor'] -1
          that.setData({ commemArr })
        }
      })
    }else{
      api.commentsaufavor({ audioid:id}, res => {
        if (res.data.issuccess == 1) {
          wx.showToast({
            title: '点赞成功',
            icon: 'none',
            duration: 1500
          })
          commemArr[index]['isfavor'] = true
          commemArr[index]['item']['favor'] = commemArr[index]['item']['favor'] + 1
          that.setData({ commemArr})
        }
      })
    }
  },
  // 转发
  share(){

  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  ChooseCheckbox(e) {
    let values = e.currentTarget.dataset.value;
    setTimeout(function(){
    //  myAudio.pause()
    },values)
    this.hideModal()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // that.setData({ state: 'play'})
    // let appletname=app.logininfo.appletname
    // console.log(appletname,'appletnameappletnameappletname');
    // wx.setNavigationBarTitle({
    //   title: appletname  || '小巴学堂',
    // })
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    that.setData({duration:0,formatDuration:'00:00'})
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    that.setData({ duration: 0 })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return{
      title: app.logininfo.appletname,
      path: '/pages/rowdata/rowdata?share=1&id=' + that.data.id+'&share='+app.logininfo.userid
    }
  },
  onShareTimeline: () => {
    let {data} = that.data
    return {
      title: data.data.title,
      imageUrl: data.imgsrc,
      query:'id='+that.data.id
    }
  },
})